/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License. You may obtain a copy of the License at
	http://www.mozilla.org/MPL/
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/

import org.aswing.ASColor;
import org.aswing.BorderLayout;
import org.aswing.Component;
import org.aswing.Event;
import org.aswing.geom.Dimension;
import org.aswing.JPanel;
import org.aswing.LayoutManager;

import com.bourre.commands.Command;
import com.bourre.commands.CommandManagerMS;
import com.bourre.commands.Delegate;
import com.bourre.core.HashCodeFactory;
import com.bourre.events.EventType;
import com.bourre.events.IEvent;
import com.bourre.medias.video.VideoDisplayEvent;

import fever.app.local.Localisation;
import fever.app.local.LocalisationEvent;
import fever.app.local.LocalisationListener;
import fever.app.menu.FvContextMenu;
import fever.app.menu.FvContextMenuEvent;
import fever.app.menu.FvContextMenuItem;
import fever.events.ApplicationEvent;
import fever.events.StageEvent;
import fever.Fever;
import fever.log.FeverDebug;
import fever.medias.video.FvVideoDisplay;
import fever.medias.video.VideoCuePointEvent;
import fever.medias.video.VideoMetaData;
import fever.utils.Stringifier;

import fvaswing.components.alert.FvAlertType;
import fvaswing.components.FvAlert;
import fvaswing.components.reader.FvReaderResources;
import fvaswing.components.reader.video.FvFullScreenPlayer;
import fvaswing.components.reader.video.FvVideoItem;

/**
 * VideoPlayer ( light version )
 * 
 * <p>Act as a classic <strong>JPanel</strong> component.<br />
 * Just append it into another component.
 * 
 * <p>Pending process allow to load video before panel is created.<br />
 * Video will be correctly displayed when panel will be created.
 * 
 * <p>Don't forget to add :
 * {@code
 *   mySWFObject.addParam( "allowFullScreen", "true" );
 * }
 * in your html document to allow fullscreen mode.
 * 
 * <p>SWF file must have a embeded movieclip named "VideoDisplay" 
 * with a Video object named "video".<br />
 * Example using swfmill
 * {@code
 *   <clip id="VideoDisplay" name="VideoDisplay">
 *       <frame>
 *   		<video id="vid" width="320" height="240" x="0" y="0" />
 *   		<place id="vid" name="video" />
 *   	</frame>
 *   </clip>
 * 
 * }
 * 
 * <p>Example
 * {@code
 *   var lite : FvVideoPlayerLite = new FvVideoPlayerLite();
 *   lite.load( "repository/video.flv" );
 *   
 *   var frame : JFrame = new JFrame( FvAsWingStage.getRootMovieClip(), "Lite player", false );
 *   frame.setResizable( true );
 *   frame.setClosable( false );
 *   
 *   var content : Container = frame.getContentPane();
 *   content.setLayout( new BorderLayout( 5,5 ) );
 *   content.append( lite, BorderLayout.CENTER );
 *   
 *   frame.setSize( 300, 200 );
 *   frame.show();
 * }
 * 
 * @author Romain Ecarnot
 */
class fvaswing.components.reader.video.FvVideoPlayerLite extends JPanel 
	implements LocalisationListener
{
	//-------------------------------------------------------------------------
	// Events definition
	//-------------------------------------------------------------------------
	
	/** Broadcasted when video is ready to play ( metadata are received ). */
	public static var onLoadInitEVENT : EventType = FvVideoDisplay.onLoadInitEVENT;
	
	/** Broadcasted when error occured during loading process. */
	public static var onErrorEVENT : EventType = FvVideoDisplay.onErrorEVENT;
	
	/** Broadcasted when fullscreen player is enabled / disabled. */
	public static var onFullScreenEVENT : EventType = new EventType( "onFullScreen" );
	
	/** Broadcasted when user toggle "play/pause" property of video. */
	public static var onVideoPlayChangeEVENT : EventType = new EventType( "onVideoPlayChange" );
	
	/** Broadcasted when user stop video. */
	public static var onVideoStopEVENT : EventType = new EventType( "onVideoStop" );
	
	/** Broadcasted when user change video volume ( not muting ). */
	public static var onVideoVolumeChangeEVENT : EventType = new EventType( "onVideoVolumeChange" );
	
	/** Broadcasted when user toggle "mute" property of current video. */
	public static var onVideoMuteEVENT : EventType = new EventType( "onVideoMute" );
	
	 /** Broadcasted when user stop video. */
	public static var onVideoPlayHeadChangeEVENT : EventType = new EventType( "onVideoPlayHeadChange" );
	
	/** Broadcasted when stream starts playing. */
	public static var onStartStreamEVENT : EventType = FvVideoDisplay.onStartStreamEVENT;
	
	/** Broadcasted when stream is finished. */
	public static var onEndStreamEVENT : EventType = FvVideoDisplay.onEndStreamEVENT;
	
	/** Broadcasted when buffer is full. */
	public static var onBufferFullEVENT : EventType = FvVideoDisplay.onBufferFullEVENT;
	
	/** Broadcasted when buffer is empty. */
	public static var onBufferEmptyEVENT : EventType = FvVideoDisplay.onBufferEmptyEVENT;
	
	
	
	//-------------------------------------------------------------------------
	// Private properties
	//-------------------------------------------------------------------------
	
	private var _resources : FvReaderResources;
	
	private var _videoMC : MovieClip;
	private var _controller : FvVideoDisplay;
	private var _holdVolume : Number;
	private var _muteState : Boolean;
	private var _fullPlayer : FvFullScreenPlayer;
	private var _alertDialog : FvAlert;
	private var _autoSize : Boolean;
	private var _fullEnabled : Boolean;
	
	// context
	private var _contextMenu : FvContextMenu;
	private var _playItemContext : FvContextMenuItem;
	private var _stopItemContext : FvContextMenuItem;
	private var _fullItemContext : FvContextMenuItem;
	private var _incVolumeContext : FvContextMenuItem;
	private var _decVolumeContext : FvContextMenuItem;
	private var _muteVolumeContext : FvContextMenuItem;
	
	private var _pendingLoad : Command; 
	private var _item : FvVideoItem;
		
	
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Constructor.
	 */
	public function FvVideoPlayerLite( )
	{
		super( new BorderLayout() );
		
		setOpaque( true );
		setBackground( ASColor.BLACK );
		
		_autoSize = false;
		_fullEnabled = true;
		
		addEventListener( JPanel.ON_CREATED, _createVideoObject, this );		addEventListener( JPanel.ON_DESTROY, _releaseVideoObject, this );		
		_resources = FvReaderResources.getInstance();
		Localisation.addLocalisationListener( this );
		
		_createContextMenu();
		_fullPlayer = new FvFullScreenPlayer();
		
		_alertDialog = new FvAlert( FvAlertType.OK_ONLY );
		_alertDialog.title = _resources.videoFullErrorTitle + " ( " + Fever.client.player.getVersion() + " )";
		_alertDialog.message = _resources.videoFullErrorMessage;
		_alertDialog.addListener( _onCloseAlertDialog, this );
		
		_muteState = false;
	}
	
	/**
	 * Sets if video will be automatically resized when loaded.
	 * Default is {@code false}
	 */
	public function setAutoSize( b : Boolean ) : Void
	{
		_autoSize = b;	
	}
	
	/**
	 * Overrides AsWing component.setLayout() method.
	 */
	public function setLayout( layout : LayoutManager ) : Void
	{
		
	}
	
	/**
	 * Overrides AsWing component.insert() method to avoid video replacement.
	 */
	public function insert( i : Number, com : Component, constraints : Object ) : Void
	{
		if( constraints != BorderLayout.CENTER )
		{
			super.insert( i, com, constraints );
		}	
		else
		{
			FeverDebug.ERROR( "can't append component on video place" );	
		}
	}
	
	/**
	 * Loads passed-in {@code url} video.
	 * 
	 * @param url flv url
	 * @param streaming ( optional ) {@code true} if use PHP Streaming service
	 */
	public function load( url : String, streaming : Boolean ) : Void
	{
		if( url && ( url != _item.getURL() ) )
		{
			if( isDisplayable() )
			{
				_controller.setPlaying( true );
				_load( url, streaming );
			}
			else
			{
				_pendingLoad = new Delegate( this, load, url, streaming );
				CommandManagerMS.getInstance().delay( _pendingLoad, 200 );	
			}
		}
	}
	
	/**
	 * setSize(width:Number, height:Number)<br>
	 * setSize(dim:Dimension)
	 */
	public function setSize() : Void
	{
		super.setSize( arguments[0], arguments[1] );
		
		var videoSize : Dimension = _item.getSize();
		var scale : Number = Math.max( videoSize.width / getWidth(), videoSize.height / getHeight() );
        var newW : Number = videoSize.width / scale;
        var newH : Number = videoSize.height / scale;
        
        _controller.setSize( newW, newH  );
        _controller.move( getWidth() / 2 - newW / 2, getHeight() / 2 - newH / 2 );
	}
	
	/**
	 * Returns metadata for current video.
	 */
	public function getMetaData() : VideoMetaData
	{
		return _controller.getMetaData();	
	}
	
	/**
	 * Returns defined cue points in current video.
	 */
	public function getCuePoints() : Array
	{
		return _controller.getCuePoints();	
	}
	
	/**
	 * Plays video
	 * 
	 * @param n ( optional ) playhead time position
	 */
	public function play( n : Number ) : Void
	{
		_controller.play( n );
		_fireEventType( onVideoPlayChangeEVENT );
	}
	
	/**
	 * Pauses video.
	 */
	public function pause(  ) : Void
	{
		_controller.pause();
		_fireEventType( onVideoPlayChangeEVENT );
	}
	
	/**
	 * Toggles play/pause
	 */
	public function toggle() : Void
	{
		if( _controller.isPlaying() ) pause();
		else play();
	}
	
	/**
	 * Move video playhead to position {@code n}
	 */
	public function seek( n : Number ) : Void
	{
		if( _item.isPHPStreaming() )
			_controller.streamFromPHP( n );
		else _controller.setPlayheadTime( n );
	}
	 
	/**
	 * Returns current playhead time.
	 */
	public function getPlayHeadTime() : Number
	{
		return _controller.getPlayheadTime();
	}
	
	/**
	 * Defines video volume value.
	 */
	public function setVolume( n : Number ) : Void
	{
		if( !_muteState )
		{
			_controller.setVolume( n );
			_fireEventType( onVideoVolumeChangeEVENT );
		}
	}
	
	/**
	 * Returns video volume.
	 */
	public function getVolume() : Number
	{
		return _controller.getVolume();	
	}
	
	/**
	 * Increases or descreases video volume by 
	 * passed-in {@code n} value.
	 * 
	 * <p>Checks if new value is in a valid range ( 0-100 ) before 
	 * sending value to the video controller.
	 */
	public function appendVolume( n : Number ) : Void
	{
		var v : Number = _controller.getVolume();
		v = v+ n;
		
		if( v > 100 ) v = 100;
		else if( v < 0 ) v = 0;
		
		setVolume( v );	
	}
	
	/**
	 * Toggles mute on/off state.
	 */
	public function mute() : Void
	{
		_muteState = !_muteState;
		
		if( _muteState )
		{
			_holdVolume = _controller.getVolume();
			_controller.setVolume( 0 );
		}
		else _controller.setVolume( _holdVolume );
		
		_fireEventType( onVideoMuteEVENT );
	}
	
	/**
	 * Returns {@code true} if volume is currently mute.
	 */
	public function isMute() : Boolean
	{
		return _muteState;	
	}
	
	/**
	 * Returns {@code true} if video is currently playing.
	 */
	public function isPlaying() : Boolean
	{
		return _controller.isPlaying();	
	}
	
	/**
	 * Stops current video
	 */
	public function stop() : Void
	{
		_controller.stop();
		_fireEventType( onVideoStopEVENT );
	}
	
 	/**
 	 * Releases document and all event listeners subscription.
 	 */
 	public function release() : Void
 	{
 		_controller.release();
 	}
 	
 	/**
 	 * Sets if fullscreen mode is enabled or not.
 	 */
 	public function setFullScreenEnabled( b : Boolean ) : Void
 	{
 		_fullEnabled = b;	
 		
 		_fullItemContext.enabled = b;
 	}
 	
 	/**
 	 * Returns {@code true} if fullscreen mode is enabled.
 	 */
 	public function isFullScreenEnabled() : Boolean
 	{
 		return _fullEnabled;	
 	}
 	
 	/**
 	 * Triggered when Localisation language change.
 	 */
 	public function onLocalisationUpdate( event : LocalisationEvent ) : Void
 	{
		_playItemContext.caption = _resources.videoPlay;
		_stopItemContext.caption = _resources.videoStop;
		_fullItemContext.caption = _resources.videoFull;
		_incVolumeContext.caption = _resources.videoIncrease;
		_decVolumeContext.caption = _resources.videoDecrease;
		_muteVolumeContext.caption = _resources.videoMute;
		
		_alertDialog.title = _resources.videoFullErrorTitle + " ( " + Fever.client.player.getVersion() + " )";
		_alertDialog.message = _resources.videoFullErrorMessage;
 	}
 	
 	/**
 	 * Returns string representation.
 	 */
 	public function toString() : String
 	{
 		return Stringifier.parse( this );
 	}
 	
 	
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
	
	private function _createVideoObject( source : JPanel ) : Void
	{
		var target : MovieClip = source.createMovieClip( "_v_", 1 );
		_videoMC = target.attachMovie( "VideoDisplay", "__video" + HashCodeFactory.getKey( this ), 1 );
		
		_controller = new FvVideoDisplay( _videoMC,  _videoMC['video'] );
		_controller.setAutoSize( _autoSize );
		_controller.setLoopPlayback( true );
		_controller.setAntiCache( false );
		_controller.addEventListener( FvVideoDisplay.onPlayHeadTimeChangeEVENT, this, _onPlayHeadChange );
		_controller.addEventListener( FvVideoDisplay.onErrorEVENT, this, _onVideoError );		_controller.addEventListener( FvVideoDisplay.onTimeOutEVENT, this, _onVideoError );
		_controller.addEventListener( FvVideoDisplay.onCuePointEVENT, this, _onCuePoint );
				_controller.addEventListener( onStartStreamEVENT, this, _bubbleEvent );		_controller.addEventListener( onEndStreamEVENT, this, _bubbleEvent );		_controller.addEventListener( onBufferFullEVENT, this, _bubbleEvent );		_controller.addEventListener( onBufferEmptyEVENT, this, _bubbleEvent );
	}
	
	private function _load( url : String, streaming : Boolean ) : Void
	{
		_videoMC.menu = null;
		
		_controller.addEventListener( FvVideoDisplay.onMetaDataEVENT, this, _onMetaData, url, streaming );
		_controller.load( url );
	}
	
 	private function _openFullScreen() : Void
 	{
 		if( Fever.client.player.isFullScreenCompliant() )
		{
			Fever.application.addEventListener( ApplicationEvent.onStateChangeEVENT, this, _onModeChanged );
			pause();
			
			_fullPlayer.open( _item, getPlayHeadTime() );
			_fireEventType( onFullScreenEVENT );
		}
		else
		{
			pause();
			_alertDialog.open();
		}	
 	}
 	
	private function _createContextMenu() : Void
	{
		_fullItemContext = new FvContextMenuItem( _resources.videoFull );
		_fullItemContext.addEventListener ( FvContextMenuEvent.onContextItemEVENT, this, _openFullScreen );
		
		_playItemContext = new FvContextMenuItem( _resources.videoPlay, true );
		_playItemContext.addEventListener ( FvContextMenuEvent.onContextItemEVENT, this, toggle );
		
		_stopItemContext = new FvContextMenuItem( _resources.videoStop );
		_stopItemContext.addEventListener ( FvContextMenuEvent.onContextItemEVENT, this, stop );
		
		_incVolumeContext = new FvContextMenuItem( _resources.videoIncrease, true );
		_incVolumeContext.addEventListener ( FvContextMenuEvent.onContextItemEVENT, this, _onContextAppendVolume, 10 );
		
		_decVolumeContext = new FvContextMenuItem( _resources.videoDecrease );
		_decVolumeContext.addEventListener ( FvContextMenuEvent.onContextItemEVENT, this, _onContextAppendVolume, -10 );
		
		_muteVolumeContext = new FvContextMenuItem( _resources.videoMute );
		_muteVolumeContext.addEventListener ( FvContextMenuEvent.onContextItemEVENT, this, mute );
		
		_contextMenu = new FvContextMenu( );
		_contextMenu.push( _muteVolumeContext );
		_contextMenu.push( _decVolumeContext );
		_contextMenu.push( _incVolumeContext );
		_contextMenu.push( _stopItemContext );
		_contextMenu.push( _playItemContext );
		_contextMenu.push( _fullItemContext );
	}
	
	private function _onContextAppendVolume( event : FvContextMenuEvent, value : Number ) : Void
	{
		appendVolume( value );	
	}
	
	private function _onPlayHeadChange( event : VideoDisplayEvent ) : Void
	{
		_fireEventType( onVideoPlayHeadChangeEVENT );
	}
	
	private function _onModeChanged( event : StageEvent ) : Void
	{
		if( _fullPlayer.isRunning() && !Fever.application.isFullScreen() )
		{
			var time : Number = _fullPlayer.getPlayHeadTime();
			_fullPlayer.close();
			
			Fever.application.removeEventListener( ApplicationEvent.onStateChangeEVENT, this );
			
			play( time );
			_fireEventType( onFullScreenEVENT );
		}
	}
	
	private function _onCloseAlertDialog() : Void
	{
		play();
	}
	
	private function _onMetaData( event : VideoDisplayEvent, url : String, streaming : Boolean ) : Void
	{
		_controller.removeEventListener( FvVideoDisplay.onMetaDataEVENT, this );
		
		onLocalisationUpdate();
		_videoMC.menu = _contextMenu.menu;
		
		_item = new FvVideoItem( url, null, streaming );
		_item.setMetaData( FvVideoDisplay( event.getTarget()).getMetaData() );
		
		revalidate();
		_fireEventType( onLoadInitEVENT );
	}
	
	private function _onVideoError( event : IEvent ) : Void
	{
		_controller.release();
		
		FeverDebug.ERROR( "video error during loading process" );
		
		_fireEventType( onErrorEVENT );
	}
	
	private function _onCuePoint( event : VideoCuePointEvent ) : Void
	{
		dispatchEvent( 
			FvVideoDisplay.onCuePointEVENT, 
			new Event( 
				this,
				FvVideoDisplay.onCuePointEVENT, 
				[ event.getCuePoint() ] 
			) 
		);
	}
	
	private function _releaseVideoObject() : Void
	{
		FeverDebug.DEBUG( "Stop video" );
		_controller.stop();
		_controller.release();
	}
	
	private function _bubbleEvent( event : IEvent ) : Void
	{
		_fireEventType( event.getType() );
	}
	
	private function _fireEventType( type : EventType) : Void
	{
		dispatchEvent( type, new Event( this, type ) );
	}

}